<template>
    <basic-container>
        <avue-crud ref="crud"
                   v-model="form"
                   v-model:page="page"
                   v-model:search="search"
                   :before-open="beforeOpen"
                   :data="data"
                   :option="option"
                   :permission="permissionList"
                   :table-loading="loading"
                   @row-update="rowUpdate"
                   @row-save="rowSave"
                   @row-del="rowDel"
                   @search-change="searchChange"
                   @search-reset="searchReset"
                   @selection-change="selectionChange"
                   @current-change="currentChange"
                   @size-change="sizeChange"
                   @on-load="onLoad">
            <template #menu-left>
                <el-button v-if="permission.enterprise_delete"
                           icon="el-icon-delete"
                           plain
                           size="small"
                           type="danger"
                           @click="handleDelete">删 除
                </el-button>
            </template>
            <template #menu="{ size, row, index }">
                <el-button :size="size"
                           icon="el-icon-setting"
                           text
                           type="primary"
                           @click="handleService(row)">
                    服务授权
                </el-button>
                <el-button :size="size"
                           icon="el-icon-setting"
                           text
                           type="primary"
                           @click="handleAdminInit(row)">
                    管理初始化
                </el-button>
            </template>
        </avue-crud>
        <el-dialog v-model="this.customService"
                   append-to-body="true"
                   height="80%"
                   title="服务授权"
                   width="50%">
            <el-table
                ref="serviceTable"
                :data="this.serviceList"
                style="width: 100%;height: 100%"
                @selection-change="handleServiceSelectionChange">
                <el-table-column
                    type="selection"
                    width="55">
                </el-table-column>
                <el-table-column
                    label="主键"
                    prop="id"
                    width="180">
                </el-table-column>
                <el-table-column
                    label="服务名"
                    prop="serviceName"
                    width="180">
                </el-table-column>
                <el-table-column
                    label="授权状态"
                    prop="authStatus">
                    <template #default="{row}">
                        {{ this.getAuthStatus(row.authStatus) }}<!--调用getChangeType方法-->
                    </template>
                </el-table-column>
            </el-table>
            <span slot="footer"
                  class="dialog-footer">
                <el-button @click="customService = false">取 消</el-button>
                <el-button @click="this.rejectService()">拒 绝</el-button>
                <el-button type="primary"
                           @click="this.submitService()">确 定</el-button>
              </span>
        </el-dialog>
        <el-dialog v-model="this.adminInit"
                   append-to-body="true"
                   height="80%"
                   title="初始化管理信息"
                   width="40%">
            <el-form :model="adminInitForm" ref="adminInitForm" label-width="150">
                <el-form-item prop="adminAccount" label="请设置管理员账号">
                    <el-input v-model="adminInitForm.adminAccount"></el-input>
                </el-form-item>
                <el-form-item prop="adminPass" label="请设置管理员密码">
                    <el-input v-model="adminInitForm.adminPass"></el-input>
                </el-form-item>
                <el-form-item prop="adminPassConfirm" label="请确认管理员密码">
                    <el-input v-model="adminInitForm.adminPassConfirmed"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer"
                  class="dialog-footer">
                <el-button @click="adminInit = false">取 消</el-button>
                <el-button type="primary"
                           @click="this.submitAdminInit()">确 定</el-button>
              </span>
        </el-dialog>
    </basic-container>
</template>

<script>
import {add, getDetail, getList, grantService, initAdmin, rejectService, remove, update} from "@/api/tenant/enterprise";
import {mapGetters} from "vuex";
import {baseUrl} from "@/config/env";
import {getEnterpriseStatusList} from "@/api/tenant/service";
import {nextTick} from "vue";
import {ElTable, ElTableColumn} from "element-plus";

export default {
    components: {
        [ElTable.name]: ElTable,
        [ElTableColumn.name]: ElTableColumn
    },
    data() {
        return {
            adminInitForm:{
                adminAccount:"",
                adminPass:"",
                adminPassConfirmed:""
            },
            form: {},
            query: {},
            search: {},
            loading: true,
            customService: false,
            adminInit: false,
            serviceSelectList: [],
            serviceList: [],
            defaultObj: [],
            treeProps: {
                label: "name",
                value: "id",
            },
            page: {
                pageSize: 10,
                currentPage: 1,
                total: 0
            },
            selectionList: [],
            option: {
                height: 'auto',
                calcHeight: 210,
                searchShow: true,
                searchMenuSpan: 6,
                tip: false,
                border: true,
                index: true,
                viewBtn: true,
                selection: true,
                column: [
                    {
                        label: "企业ID",
                        prop: "id",
                        rules: [{
                            required: true,
                            message: "请输入企业ID",
                            trigger: "blur"
                        }]
                    },
                    {
                        label: "企业名称",
                        prop: "enterpriseName",
                        rules: [{
                            required: true,
                            message: "请输入企业名称",
                            trigger: "blur"
                        }]
                    },
                    {
                        label: "企业代码",
                        prop: "enterpriseCode",
                        rules: [{
                            required: true,
                            message: "请输入企业代码",
                            trigger: "blur"
                        }]
                    },
                    {
                        label: "统一社会信用代码",
                        prop: "creditCode",
                        rules: [{
                            required: true,
                            message: "请输入统一社会信用代码",
                            trigger: "blur"
                        }]
                    },
                    {
                        label: "行业类型",
                        prop: "industryType",
                        rules: [{
                            required: true,
                            message: "请输入行业类型",
                            trigger: "blur"
                        }]
                    },
                    {
                        label: "企业类型",
                        prop: "enterpriseType",
                        rules: [{
                            required: true,
                            message: "请输入企业类型",
                            trigger: "blur"
                        }]
                    },
                    {
                        label: "所在区域",
                        prop: "region",
                        rules: [{
                            required: true,
                            message: "请输入所在区域",
                            trigger: "blur"
                        }]
                    },
                    {
                        label: "企业规模",
                        prop: "enterpriseSize",
                        rules: [{
                            required: true,
                            message: "请输入企业规模",
                            trigger: "blur"
                        }]
                    },
                    {
                        label: "所属租户",
                        prop: "tenantId",
                        type: "tree",
                        dicUrl: baseUrl + "/ucs-system/tenant/select",
                        props: {
                            label: "tenantName",
                            value: "tenantId"
                        },
                        rules: [{
                            required: true,
                            message: "请输入租户ID",
                            trigger: "blur"
                        }]
                    },
                    {
                        label: "负责人",
                        prop: "chargePerson",
                        hide: true,
                        rules: [{
                            required: true,
                            message: "请输入负责人",
                            trigger: "blur"
                        }]
                    },
                    {
                        label: "负责人职位",
                        prop: "position",
                        hide: true,
                        rules: [{
                            required: true,
                            message: "请输入负责人职位",
                            trigger: "blur"
                        }]
                    },
                    {
                        label: "负责人电话",
                        prop: "phone",
                        hide: true,
                        rules: [{
                            required: true,
                            message: "请输入负责人电话",
                            trigger: "blur"
                        }]
                    },
                    {
                        label: "负责人邮箱",
                        prop: "email",
                        hide: true,
                        rules: [{
                            required: true,
                            message: "请输入负责人邮箱",
                            trigger: "blur"
                        }]
                    },
                    {
                        label: "备注信息",
                        prop: "remarks",
                        hide: true,
                        rules: [{
                            required: false,
                            message: "请输入备注信息",
                            trigger: "blur"
                        }]
                    },
                ]
            },
            data: []
        };
    },
    computed: {
        ...mapGetters(["permission"]),
        permissionList() {
            return {
                addBtn: this.validData(this.permission.enterprise_add, false),
                viewBtn: this.validData(this.permission.enterprise_view, false),
                delBtn: this.validData(this.permission.enterprise_delete, false),
                editBtn: this.validData(this.permission.enterprise_edit, false)
            };
        },
        ids() {
            let ids = [];
            this.selectionList.forEach(ele => {
                ids.push(ele.id);
            });
            return ids.join(",");
        },
        serviceIds() {
            let sids = [];
            this.serviceSelectList.forEach(ele => {
                sids.push(ele.id);
            });
            return sids.join(",");
        },

    },
    methods: {
        getAuthStatus(aStatus) {
            switch (aStatus) {
                case 0:
                    return "申请中";
                case 1:
                    return "已开通";
                default:
                    return "未授权";
            }
        },
        initServiceSelection() {
            // val 是一个包含选中行数据的数组
            this.serviceSelectList = [];
            this.serviceList.forEach(row => {
                console.log(row.authStatus);
                if (row.authStatus != null) {
                    this.serviceSelectList.push(row.id);
                    nextTick(() => { //数据加载，dom构建完再进行选择事件
                        this.$refs.serviceTable.toggleRowSelection(row, true);
                    });
                } else {
                    this.serviceSelectList.push(row.id);
                    nextTick(() => { //数据加载，dom构建完再进行选择事件
                        this.$refs.serviceTable.toggleRowSelection(row, false);
                    });

                }
            });
        },
        handleServiceSelectionChange(val) {
            // val 是一个包含选中行数据的数组
            this.serviceSelectList = val;
            console.log('当前选中项', val);
        },
        submitService() {
            const serviceLIst = this.serviceIds;
            this.$confirm("确定调整此企业服务？", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(() => {
                    grantService(this.rowid, serviceLIst).then(() => {
                        this.customService = false;
                        this.$message({
                            type: "success",
                            message: "操作成功!"
                        });
                        this.onLoad(this.page);
                    })
                });

        },
        rejectService() {
            const serviceLIst = this.serviceIds;
            this.$confirm("确定调整此企业服务？", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(() => {
                    rejectService(this.rowid, serviceLIst).then(() => {
                        this.customService = false;
                        this.$message({
                            type: "success",
                            message: "操作成功!"
                        });
                        this.onLoad(this.page);
                    });
                });
        },
        rowSave(row, done, loading) {
            add(row).then(() => {
                done();
                this.onLoad(this.page);
                this.$message({
                    type: "success",
                    message: "操作成功!"
                });
            }, error => {
                window.console.log(error);
                loading();
            });
        },
        rowUpdate(row, index, done, loading) {
            update(row).then(() => {
                done();
                this.onLoad(this.page);
                this.$message({
                    type: "success",
                    message: "操作成功!"
                });
            }, error => {
                window.console.log(error);
                loading();
            });
        },
        rowDel(row) {
            this.$confirm("确定将选择数据删除?", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(() => {
                    return remove(row.id);
                })
                .then(() => {
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                });
        },
        handleAdminInit(row) {
            this.rowid = row.id;
            this.adminInitForm.adminAccount=row.enterpriseCode+"_admin"
            this.adminInit = true;
        },
        submitAdminInit(){
            console.log("submit admin init!");
            this.$confirm("确定初始化此企业的管理员数据?", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(() => {
                    return initAdmin(this.rowid,this.adminInitForm);
                })
                .then(() => {
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                    this.adminInit = false;
                });
        },
        handleService(row) {
            this.rowid = row.id;
            this.defaultObj = [];
            return getEnterpriseStatusList(row.id)
                .then(res => {
                    this.customService = true;
                    this.serviceList = res.data.data;
                    this.initServiceSelection();

                });
        },
        handleDelete() {
            if (this.selectionList.length === 0) {
                this.$message.warning("请选择至少一条数据");
                return;
            }
            this.$confirm("确定将选择数据删除?", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(() => {
                    return remove(this.ids);
                })
                .then(() => {
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                    this.$refs.crud.toggleSelection();
                });
        },
        beforeOpen(done, type) {
            if (["edit", "view"].includes(type)) {
                getDetail(this.form.id).then(res => {
                    this.form = res.data.data;
                });
            }
            done();
        },
        searchReset() {
            this.query = {};
            this.onLoad(this.page);
        },
        searchChange(params, done) {
            this.query = params;
            this.page.currentPage = 1;
            this.onLoad(this.page, params);
            done();
        },
        selectionChange(list) {
            this.selectionList = list;
        },
        selectionClear() {
            this.selectionList = [];
            this.$refs.crud.toggleSelection();
        },
        currentChange(currentPage) {
            this.page.currentPage = currentPage;
        },
        sizeChange(pageSize) {
            this.page.pageSize = pageSize;
        },
        onLoad(page, params = {}) {
            this.loading = true;
            getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
                const data = res.data.data;
                this.page.total = data.total;
                this.data = data.records;
                this.loading = false;
                this.selectionClear();
            });
        }
    }
};
</script>

<style>
</style>
